from typing import List, Optional

from sqlalchemy.orm import Session

from app.crud.base import CRUDBase
from app.models.sys_config import SysConfig
from app.schemas.sys_config import SysConfigCreate, SysConfigUpdate


class CRUDSysConfig(CRUDBase[SysConfig, SysConfigCreate, SysConfigUpdate]):
    """
    系统配置CRUD操作
    """
    
    def get_by_code(self, db: Session, *, code: str) -> Optional[SysConfig]:
        """
        根据配置代码获取配置
        """
        return db.query(SysConfig).filter(SysConfig.code == code).first()
    
    def get_value_by_code(self, db: Session, *, code: str, default_value: str = None) -> Optional[str]:
        """
        根据配置代码获取配置值
        """
        config = self.get_by_code(db, code=code)
        if config and config.value:
            return config.value
        return default_value
    
    def search_by_code(self, db: Session, *, code: str = None, skip: int = 0, limit: int = 100) -> List[SysConfig]:
        """
        根据代码模糊搜索配置
        """
        query = db.query(SysConfig)
        if code:
            query = query.filter(SysConfig.code.like(f"%{code}%"))
        return query.offset(skip).limit(limit).all()
    
    def count_by_code(self, db: Session, *, code: str = None) -> int:
        """
        统计配置数量
        """
        query = db.query(SysConfig)
        if code:
            query = query.filter(SysConfig.code.like(f"%{code}%"))
        return query.count()


# 创建实例以便导入
sys_config = CRUDSysConfig(SysConfig)